package com.at;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.MessageFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class LoadTester {

    public static final AtomicInteger counter = new AtomicInteger(0);
    private final int connectionCount;

    String url;

    int failureCount;
    int successCount;

    ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) throws InterruptedException {
        LoadTester loadTester1 = new LoadTester("http://localhost:8080/tomcat-async-test/simple", 2);
        LoadTester loadTester2 = new LoadTester("http://localhost:8080/tomcat-async-test/AsyncLongRunningServlet", 100);
//        loadTester2.start();
        Thread.sleep(5000);
        loadTester1.start();
        loadTester1.awaitTermination();
//        loadTester2.awaitTermination();
    }

    public LoadTester(String url, int connectionCount) {
        this.url = url;
        this.connectionCount = connectionCount;
    }

    public void start() throws InterruptedException {
        for (int i = 0; i < connectionCount; i++) {
            executorService.submit(new UrlReaderTask(url, i));
        }
    }

    public void awaitTermination() throws InterruptedException {
        executorService.shutdown();
        executorService.awaitTermination(3, TimeUnit.HOURS);
        System.out.println("------------------------------------------------------");
        System.out.println("LoadTester for: "+url);
        System.out.println("successes: " + successCount);
        System.out.println("failures: " + failureCount);
    }

    public class UrlReaderTask implements Runnable {

        private final String endpoint;
        private final int id;

        public UrlReaderTask(String s, int id) {
            endpoint = s + "?id=" + id;
            this.id = id;
        }

        @Override
        public void run() {
            String url = endpoint + "&time=" + 3000;
            final long t1 = System.currentTimeMillis();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
                StringBuilder sb = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    sb.append(inputLine);
                    sb.append(": ");
                }
                final long t2 = System.currentTimeMillis();
                System.out.println(MessageFormat.format("thread[{0}] : {1} took {2} sec", id, sb, (t2-t1)/1000));
                successCount++;
            } catch (Exception e) {
                failureCount++;
                System.err.println(id + ": " + e.toString());
            }
        }
    }

}
